#coding:utf-8
import os
import pathlib
import requests
import json
from bs4 import BeautifulSoup
import time

Now_day = time.localtime().tm_year*10000+time.localtime().tm_mon*100+time.localtime().tm_mday
Now_day = str(Now_day)
#https://n8k6e2y6.ssl.hwcdn.net/repos/hnfvc0o3jnfvc873njb03enrf56.html#relicRewards
#PC 平台官方掉落表
#获取杜卡德金币数据
file_name="ducats_"+Now_day+".txt"
my_file = pathlib.Path(file_name)
if my_file.is_file():
    print("今日已更新")
    exit()

def get_ducats():
    r = requests.get('https://warframe.market/tools/ducats')
    #print(r.status_code)
    #print(r.text)
    #<script type="application/json" id="application-state"> 本地数据
    soup = BeautifulSoup(r.text,'lxml')
    #json数据
    ducats=json.loads(soup('script')[2].string)
    temp=json.dumps(ducats)
    f=open(r"ducats.json","w")
    temp="var ducats =" +temp
    f.write(temp)
    f.close()
    return ducats

try:
    ducats = get_ducats()
    print("联网数据")
except:
    f=open("ducats.json","r")
    temp=f.read()
    f.close()
    for i in range(len(temp)):
        if (temp[i]=="{"):
            temp=temp[i:]
            break
    ducats=json.loads(temp)
    print("本地数据")

DucatsItemDic={}
for i in ducats["items"]:
    DucatsItemDic[i["id"]]=i["item_name"]

DucatsItemData={}
for i in ducats["payload"]["previous_day"]:
    DucatsItemData[DucatsItemDic[i["item"]]]={
        "ducats":i["ducats"],
        "wa_price":i["wa_price"],
        "ducats_per_platinum_wa":i["ducats_per_platinum_wa"]
        }
#DucatsItemData[item]={"ducats":0,"wa_price":0,"ducats_per_platinum_wa":0}
print("获取杜卡德金币价值数据",DucatsItemData)



f=open(r"ItemPrice.txt","w")
temp="Item,price\n"
for i in DucatsItemData:
    temp+=i+","+str(DucatsItemData[i]["wa_price"])+"\n"
f.write(temp)
f.close()
print("杜卡德金币价值数据写入txt")

#获取结构化的核桃明细
class data_void:
    void_url="https://warframe.fandom.com/wiki/Module:Void/data"
    void_str=""
    RelicData={}
    def spy_string(self):#爬英文wiki获取字符串化数据
        print("爬英文wiki获取字符串化数据")
        r = requests.get(self.void_url)
        soup = BeautifulSoup(r.text,'lxml')
        void_data=soup.find_all('pre')[4].string
        str_star=void_data.find("RelicData = {\n")
        void_data=void_data[str_star:]
        j,str_star=-1,0
        for i in void_data:
            str_star+=1
            if (i=="{"):
                if (j==-1):j=1
                else: j+=1
            elif (i=="}"):j-=1
            if(j==0):break
        void_data=void_data[:str_star]
        #void_data=void_data.replace("\n","").replace("\t","").replace("[","").replace("]","")
        #void_data=void_data.replace("=",":").replace("\t","").replace("[","").replace("]","")
        temp=void_data.replace("\t","").replace("[","").replace("]","").replace("\n","").replace(" = ",":").replace(",}","}").replace("  "," ")
        temp=temp.replace("Lith ","古纪 ").replace("Meso ","前纪 ").replace("Neo ","中纪 ").replace("Axi ","后纪 ").replace("Requiem ","安魂 ")
        for i in range(len(temp)):
            if (temp[i]=="{"):
                temp=temp[i:]
                break
        self.void_str=temp
        #print(temp[:1000])
    def parse_str(self):#按核桃名拆分
        #按核桃名拆分
        _void=""
        len_max=len(self.void_str)
        cont_num=0
        while(cont_num<len_max):
            if self.void_str[cont_num]!='"':
                cont_num+=1
                continue
            else:
                #按核桃名拆分
                cont_num+=1
                i=1
                while(self.void_str[cont_num+i]!='"'):
                    i+=1
                _void=self.void_str[cont_num:cont_num+i]
                cont_num = cont_num + i + 2
                cont_end = cont_num
                cont_flag=0
                #print(self.void_str[cont_num:cont_num+5])
                for i in self.void_str[cont_num:]:
                    if(i=='{'):cont_flag+=1
                    elif(i=='}'):cont_flag-=1
                    cont_end+=1
                    if(cont_flag==0):break
                self.RelicData[_void]=self.void_str[cont_num:cont_end]
                cont_num=cont_end
        #print(self.RelicData)
    def parse_data(self):#对核桃内容进行解析
        for void in self.RelicData:
            line=self.RelicData[void]
            self.RelicData[void]={"Drops":[]}
            if("Vaulted" in line or "IsBaro" in line):#判断是否入库
                self.RelicData[void]["Vaulted"]=True
            else:self.RelicData[void]["Vaulted"]=False
            line=line[1:-1]
            #提出结构数据
            cont_star,cont_end,cont_flag=0,0,0
            for i in line:
                if(cont_flag==0 and i!="{"):
                    cont_star+=1
                    cont_end=cont_star
                    continue
                if(i=='{'):cont_flag+=1
                elif(i=='}'):cont_flag-=1
                cont_end+=1
                if(cont_flag==0):break
            line=line[cont_star+1:cont_end-1]
            #按部件提取
            cont_star,cont_end,cont_flag=0,0,0
            for i in line:
                if(cont_flag==0 and i!="{"):
                    cont_star+=1
                    cont_end=cont_star
                    continue
                if(i=='{'):cont_flag+=1
                elif(i=='}'):cont_flag-=1
                cont_end+=1
                if(cont_flag==0):
                    part=line[cont_star:cont_end]
                    #print(part)
                    cont_star=cont_end
                    temp=json.loads(part)
                    self.RelicData[void]["Drops"].append(temp)
        print(self.RelicData)
    def save_data(self):#使用json保存核桃结构化数据
        temp=json.dumps(self.RelicData)
        f=open(r"RelicData.json","w")
        temp="var RelicData =" +temp
        f.write(temp)
        f.close()
    def read_data(self):
        #读取json保存的核桃数据
        f=open(r"RelicData.json","r")
        temp=f.read()
        f.close()
        for i in range(len(temp)):
            if (temp[i]=="{"):
                temp=temp[i:]
                break
        self.RelicData=json.loads(temp)

temp=data_void()
temp.spy_string()
temp.parse_str()
temp.parse_data()
temp.save_data()
RelicData=temp.RelicData

def item_ptice(item_name):
    price=0
    try:
        price=DucatsItemData[item_name]["wa_price"]
    except KeyError:
        if("Blueprint" in item_name and "Kavasa" not in item_name):
            item_name=item_name[:-10]
        if(item_name=="Kavasa Prime Collar Blueprint"):
            item_name="Kavasa Prime Kubrow Collar Blueprint"
        if(item_name=="Kavasa Prime Kubrow Collar Buckle"):
            item_name="Kavasa Prime Buckle"
        if(item_name=="Kavasa Prime Kubrow Collar Band"):
            item_name="Kavasa Prime Band"
        price=DucatsItemData[item_name]["wa_price"]
    return price

#计算核桃价值
RelicPrice={}
#遗物	完	光	差	类
#常见,Common     罕见,Uncommon    稀有,Rare
#完整	76% (25.33%)	22% (11%)	2%
#光辉	50% (16.67%)	40% (20%)	10%
#四光   0.0625    0.5936   0.3439   
def cont_price(RelicName):
    RelicPrice[RelicName]={"系数":0,"类别":""}
    print(RelicName)
    for i in range(6):
        if(RelicData[RelicName]["Drops"][i]["Item"]=="Forma"):
            print("Forma")
            continue
        _item=RelicData[RelicName]["Drops"][i]["Item"]+" "+RelicData[RelicName]["Drops"][i]["Part"]
        #DucatsItemData[item]={"ducats":0,"wa_price":0,"ducats_per_platinum_wa":0}
        if(RelicData[RelicName]["Drops"][i]["Rarity"]=="Common"):
            RelicPrice[RelicName]["系数"]+=(item_ptice(_item)*0.0625/3)
        elif(RelicData[RelicName]["Drops"][i]["Rarity"]=="Uncommon"):
            RelicPrice[RelicName]["系数"]+=(item_ptice(_item)*0.5936)
        else:#稀有
            RelicPrice[RelicName]["系数"]+=(item_ptice(_item)*0.3439)
        print(_item,item_ptice(_item),RelicData[RelicName]["Drops"][i]["Rarity"])
    RelicPrice[RelicName]["系数"]=round(RelicPrice[RelicName]["系数"],2)
    if(RelicName[:2]=="古纪"):RelicPrice[RelicName]["类别"]="T1"
    elif(RelicName[:2]=="前纪"):RelicPrice[RelicName]["类别"]="T2"
    elif(RelicName[:2]=="中纪"):RelicPrice[RelicName]["类别"]="T3"
    else:RelicPrice[RelicName]["类别"]="T4"
    print(RelicPrice[RelicName])
    pass

for RelicName in RelicData:
    if ("Requiem" in RelicName or "安魂" in RelicName):
        continue
    cont_price(RelicName)

#获取中英对照表
def get_WF_Dict():
    r = requests.get('https://raw.githubusercontent.com/Richasy/WFA_Lexicon/WFA5/WF_Dict.json')
    r_json=json.loads(r.text)
    _dict={}
    for i in r_json:
        _dict[i["en"]]=i["zh"]
        print(i["en"]+":"+i["zh"])
    f_1=open(r"WF_Dict.json","w")
    temp=json.dumps(_dict)
    temp="var WF_Dict =" +temp
    f_1.write(temp)
    f_1.close()
    return _dict

try:
    last_time=os.path.getmtime('WF_Dict.json')
    _dict = get_WF_Dict()
    print("联网数据")
except:
    f=open(r"WF_Dict.json","r")
    temp=f.read()
    f.close()
    for i in range(len(temp)):
        if (temp[i]=="{"):
            temp=temp[i:]
            break
    _dict=json.loads(temp)
    print("本地数据")
    #读取本地文件

#根据名字及词典翻译
def en_to_zh(_key,flag=False):
    zh_name=""
    if(_key=="Gauntlet"):return "拳套"
    if (" "in _key):
        max_char_num=len(_key)
        try:
            zh_name=_dict[_key]
        except KeyError:
            #print(_key+"0000"+_key[-5:])
            if(_key[-5:]=="Prime"):
                #print("1111111111111111111111")
                try:
                    zh_name=en_to_zh(_key[:-6])+" Prime"
                    #print("#####"+zh_name+"#####")
                    return zh_name
                except KeyError:
                    return _key
            if(flag):
                raise KeyError
            for i in range(max_char_num):
                if(_key[max_char_num-i-1]==" "):
                    try:
                        #print("####"+_key[:max_char_num-i-1]+"####"+_key[max_char_num-i:]+"####")
                        zh_name=en_to_zh(_key[:max_char_num-i-1],True)+en_to_zh(_key[max_char_num-i:])
                        return zh_name
                    except KeyError:
                        continue
            zh_name=_key             
    else:
        try:
           zh_name=_dict[_key]
        except KeyError:
           zh_name=_key
    return zh_name

en_to_zh("Vauban Prime Neuroptics Blueprint")
en_to_zh("Paris Prime Upper Limb")
en_to_zh("Kavasa Prime Kubrow Collar Blueprint")
#Aksomati Prime Blueprint

#生成部件词典
PartName_zh={}
_item=""
_Rarity=""
for item_name in RelicData:
    for i in range(6):
        if(RelicData[item_name]["Drops"][i]["Item"]=="Forma"):
                continue
        _item=RelicData[item_name]["Drops"][i]["Item"]+" "+RelicData[item_name]["Drops"][i]["Part"]
        PartName_zh[_item]=en_to_zh(_item)

#输出验证
for item_name in PartName_zh:
    print(item_name,PartName_zh[item_name])

f_1=open(r"PartName_zh.json","w")
temp=json.dumps(PartName_zh)
temp="var PartName_zh =" +temp
f_1.write(temp)
f_1.close()

#添加核桃金部件是啥
for item_name in RelicPrice:
    _item=""
    #print (item_name)
    #print (RelicPrice[item_name])
    #print (RelicData[item_name]["Drops"][5]["Item"])
    #print (RelicData[RelicName]["Drops"][5]["Rarity"])
    _item=RelicData[item_name]["Drops"][5]["Item"]+" "+RelicData[item_name]["Drops"][5]["Part"]
    #print (_item)
    RelicPrice[item_name]["金"]=en_to_zh(_item)

f=open(r"RelicPrice_en.txt","w")
f.write("遗物,系数,类,金\n")
for RelicName in RelicPrice:
    f.write(RelicName+","+str(RelicPrice[RelicName]["系数"])+","+RelicPrice[RelicName]["类别"]+","+RelicPrice[RelicName]["金"]+"\n")

f.close()

f=open(file_name,"w")
f.write("遗物,系数,类,金\n")
for RelicName in RelicPrice:
    f.write(RelicName+","+str(RelicPrice[RelicName]["系数"])+","+RelicPrice[RelicName]["类别"]+","+RelicPrice[RelicName]["金"]+"\n")

f.close()


temp=json.dumps(RelicPrice)
f=open(r"RelicPrice.json","w")
temp="var RelicPrice =" +temp
f.write(temp)
f.close()


#出库核桃部件收集统计
#核桃数据数据格式
'''
{
    "Drops":[
        {"Item":"","Part":"","Rarity":""},
        {"Item":"","Part":"","Rarity":""},
        {"Item":"","Part":"","Rarity":""},
        {"Item":"","Part":"","Rarity":""},
        {"Item":"","Part":"","Rarity":""},
        {"Item":"","Part":"","Rarity":""}]
    "Vaulted":False
}
'''
IntroducedPart={}
_item=""
_Rarity=""
for item_name in RelicData:
    if("Requiem" in item_name):
        continue
    if(not RelicData[item_name]["Vaulted"]):
        for i in range(6):
            if(RelicData[item_name]["Drops"][i]["Item"]=="Forma"):
                continue
            _item=RelicData[item_name]["Drops"][i]["Item"]+" "+RelicData[item_name]["Drops"][i]["Part"]
            if(RelicData[item_name]["Drops"][i]["Rarity"]=="Common"):
                _Rarity="铜"
            elif(RelicData[item_name]["Drops"][i]["Rarity"]=="Uncommon"):
                _Rarity="银"
            else:
                _Rarity="金"
            try:
                IntroducedPart[_item].append({"Relic":item_name,"Rarity":_Rarity})
            except KeyError:
                IntroducedPart[_item]=[{"Relic":item_name,"Rarity":_Rarity}]

temp=json.dumps(IntroducedPart)
f=open(r"IntroducedPart.json","w")
temp="var IntroducedPart =" +temp
f.write(temp)
f.close()

Introduced_Item=[]
def Show_Introduced():
    for item_name in RelicData:
        if("Requiem" in item_name):
            continue
        if(not RelicData[item_name]["Vaulted"]):
            for i in range(6):
                _item=RelicData[item_name]["Drops"][i]["Item"]
                if (_item in Introduced_Item):
                    continue
                else:
                    Introduced_Item.append(_item)
    pass
    print(Introduced_Item)
Show_Introduced()



exit()